package tsinghua.smxq.weather;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

public class WeatherInfo {
	List<Weather> weatherList;

	public List<Weather> setWeatherInfo(String city) {
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {
			SAXParser sp = spf.newSAXParser();
			XMLReader reader = sp.getXMLReader();

			XMLHandler handler = new XMLHandler();
			reader.setContentHandler(handler);
			// 输入流，获取谷歌的天气数据
			URL url = new URL("http://www.google.com/ig/api?hl=zh-cn&weather="
					+ URLEncoder.encode(city));
			InputStream is = url.openStream();
			InputStreamReader isr = new InputStreamReader(is, "GBK");
			InputSource source = new InputSource(isr);
			// 将数据流转换成XML
			reader.parse(source);
			// 获取读取XML的list
			weatherList = handler.getWeatherList();
			return weatherList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String getCurrentInfo(String city) {
		setWeatherInfo(city);
		String weatherInfo = weatherList.get(0).getCondition() + ","
				+ weatherList.get(0).getTemp_c() + "℃,"
				+ weatherList.get(0).getWind_condition();
		return weatherInfo;
	}

}
